<template>
  <div>
    <div class="header">
      <div class="header_item" :class="activeIndex === 0 ? 'active' : ''" @click="activeIndex = 0">
        已结算
      </div>
      <div class="header_item" :class="activeIndex === 1 ? 'active' : ''" @click="activeIndex = 1">
        全部问题
      </div>
      <div class="header_item" :class="activeIndex === 2 ? 'active' : ''" @click="activeIndex = 2">
        待结算
      </div>
    </div>
    <div v-if="userProblem.length !== 0" class="problem-list">
      <div v-for="item in userProblem" :key="item.Id">
        <el-card
          class="card"
          @click="goUserQuestionDetail(item)"
          style="cursor: pointer; width: 100%"
        >
          <div class="card-title">{{ item.ProblemName }}</div>
          <div class="card-footer">
            <el-tag type="success" effect="light" round class="newtag">
              {{ item.Tag }}
            </el-tag>
            <span class="money">
              {{ item.Money === 0 ? '无悬赏' : item.Money.toFixed(2) + '元悬赏' }}
            </span>
            <span style="padding: 0 30px">{{ item.account + '条回答' }}</span>

            <span class="time">{{ convertISO8601ToSimplified(item.Time) }}</span>
            <span class="status bule" v-if="item.Status === 2">已结算</span>
            <span class="status" :class="item.Status === 0 ? 'red' : 'green'">
              {{ item.Status === 0 ? '被封禁' : '状态正常' }}
            </span>
            <el-button
              class="settle-problem"
              type="primary"
              round
              plain
              v-if="item.Status === 1 && item.Money !== 0"
              @click.stop="settleProblem(item.Id)"
              >结 算</el-button
            >
          </div>
          <el-button
            v-if="item.Status != 0"
            class="delete-button"
            type="warning"
            round
            plain
            @click.stop="clickDeleteProblem(item.Id)"
            >删 除</el-button
          >
        </el-card>
      </div>
    </div>
    <div v-else class="tishi">你还没有发表过问题哦</div>
    <el-dialog v-model="showDelete" title="删除问题" width="500" style="text-align: center">
      <div>是否确认删除问题</div>
      <div>
        <el-button type="primary" plain @click="deleteProblem()">确 定</el-button>
        <el-button plain @click="showDelete = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import {
  getUserProblemAPI,
  settleProblemAPI,
  deleteProblemAPI,
  getAnswerCountAPI
} from '@/api/user'
import { useUserStore, useUserQuestionStore } from '@/stores'
import router from '@/router'
import { watch } from 'vue'

const activeIndex = ref(1)
watch(activeIndex, async (newValue) => {
  await getUserProblem()
  if (newValue === 0) {
    userProblem.value = userProblem.value.filter((item) => item.Status === 2)
  } else if (newValue === 2) {
    userProblem.value = userProblem.value.filter((item) => item.Status === 1 && item.Money !== 0)
  }
})
const showDelete = ref(false)
const deleteProblemId = ref(-1)
const clickDeleteProblem = (ProblemId) => {
  deleteProblemId.value = ProblemId
  showDelete.value = true
}
const deleteProblem = async () => {
  const res = await deleteProblemAPI({
    ProblemId: deleteProblemId.value
  })
  if (res.data === 1) {
    await getUserProblem()
    showDelete.value = false

    ElMessage({ message: '删除成功', type: 'success' })
  } else {
    ElMessage.error('删除失败')
  }
}

const userStore = useUserStore()
const userQuestionStore = useUserQuestionStore()

const goUserQuestionDetail = (UserQuestion) => {
  if (UserQuestion.Status === 0) {
    ElMessage.error('该回答已封禁，无法查看')
    return
  }
  userQuestionStore.removeUserQuestionInfo()
  userQuestionStore.setUserQuestionInfo(UserQuestion)
  router.push({ path: '/home/user/UserQuestionDetail' })
}

const userProblem = ref([])
const getAnswerCount = async (ProblemId) => {
  const res = await getAnswerCountAPI({ ProblemId })
  console.log(res.data)
  let a = String(res.data)
  return a
}
const getUserProblem = async () => {
  const res = await getUserProblemAPI({
    UserName: userStore.userInfo.userName
  })
  console.log('我发布的问题', res)
  userProblem.value = res.data
  var a = activeIndex.value
  activeIndex.value = 0
  activeIndex.value = a
  for (const item of userProblem.value) {
    item.account = await getAnswerCount(item.Id)
  }
}

const settleProblem = async (Id) => {
  try {
    const res = await settleProblemAPI({ Id })
    if (res.data === 1) {
      await getUserProblem() // 确保获取问题列表
      ElMessage({ message: '结算成功', type: 'success' })
    } else if (res.data === 0) {
      ElMessage.error('请先给回答评分')
    } else {
      ElMessage.error('该问题暂无回答，悬赏失败')
    }
  } catch (error) {
    console.error('结算请求失败:', error)
    ElMessage.error('问题无回答或未评分')
  }
}

const convertISO8601ToSimplified = (isoString) => {
  const date = new Date(isoString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
  getUserProblem()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 20px;
  line-height: 45px;
  border-radius: 45px;
  background-color: #f4f4f4;
}
.header_item {
  flex: 1;
  text-align: center;
  height: 45px;
  line-height: 45px;
  border-radius: 45px;
}
.active {
  background-color: #000;
  color: #fff;
  animation-name: slideInLeft;
  animation-duration: 0.5s;
}
@keyframes slideInLeft {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}
.delete-button {
  position: absolute;
  right: 20px;
  top: 10px;
}
.tishi {
  text-align: center;
  font-size: 40px;
  padding-top: 40px;
}
.problem-list {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 问题卡片之间的间距 */
}
.card {
  position: relative;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transition:
    transform 0.3s,
    box-shadow 0.3s;
}
.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}
.card-title {
  font-weight: bold;
  font-size: 20px;
  line-height: 20px;
  margin: 15px;
}
.newtag {
  margin: 0 5px;
}
.money {
  font-weight: 600;
}
.time {
  margin-left: 10px;
  font-size: 12px;
  line-height: 12px;
}
.status {
  margin-left: 20px;
}
.red {
  color: red;
}
.green {
  color: green;
}
.bule {
  color: blue;
}
.settle-problem {
  float: right;
}
</style>
